import re
from flask import request


def validate_required_fields(required_fields):
    """验证必填字段"""
    data = request.get_json() or {}
    missing_fields = []
    
    for field in required_fields:
        if field not in data or data[field] is None or str(data[field]).strip() == '':
            missing_fields.append(field)
    
    if missing_fields:
        return False, f"缺少必填字段: {', '.join(missing_fields)}"
    
    return True, None


def validate_email(email):
    """验证邮箱格式"""
    if not email:
        return True  # 允许为空
    
    pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
    return bool(re.match(pattern, email))


def validate_phone(phone):
    """验证手机号格式"""
    if not phone:
        return True  # 允许为空
    
    pattern = r'^1[3-9]\d{9}$'
    return bool(re.match(pattern, phone))


def validate_username(username):
    """验证用户名格式"""
    if not username:
        return False
    
    # 用户名只能包含字母、数字、下划线，长度4-20位
    pattern = r'^[a-zA-Z0-9_]{4,20}$'
    return bool(re.match(pattern, username)) 